/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.smarttmt.smartmanager.controller;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.smarttmt.smartmanager.entity.Activida;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import org.smarttmt.smartmanager.controller.exceptions.NonexistentEntityException;
import org.smarttmt.smartmanager.controller.exceptions.PreexistingEntityException;
import org.smarttmt.smartmanager.controller.exceptions.RollbackFailureException;
import org.smarttmt.smartmanager.entity.Estrcheq;

/**
 *
 * @author nicolas
 */
public class EstrcheqJpaController implements Serializable {

    public EstrcheqJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Estrcheq estrcheq) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (estrcheq.getActividaList() == null) {
            estrcheq.setActividaList(new ArrayList<Activida>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<Activida> attachedActividaList = new ArrayList<Activida>();
            for (Activida actividaListActividaToAttach : estrcheq.getActividaList()) {
                actividaListActividaToAttach = em.getReference(actividaListActividaToAttach.getClass(), actividaListActividaToAttach.getActicodi());
                attachedActividaList.add(actividaListActividaToAttach);
            }
            estrcheq.setActividaList(attachedActividaList);
            em.persist(estrcheq);
            for (Activida actividaListActivida : estrcheq.getActividaList()) {
                Estrcheq oldActilichOfActividaListActivida = actividaListActivida.getActilich();
                actividaListActivida.setActilich(estrcheq);
                actividaListActivida = em.merge(actividaListActivida);
                if (oldActilichOfActividaListActivida != null) {
                    oldActilichOfActividaListActivida.getActividaList().remove(actividaListActivida);
                    oldActilichOfActividaListActivida = em.merge(oldActilichOfActividaListActivida);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findEstrcheq(estrcheq.getEschcodi()) != null) {
                throw new PreexistingEntityException("Estrcheq " + estrcheq + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Estrcheq estrcheq) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Estrcheq persistentEstrcheq = em.find(Estrcheq.class, estrcheq.getEschcodi());
            List<Activida> actividaListOld = persistentEstrcheq.getActividaList();
            List<Activida> actividaListNew = estrcheq.getActividaList();
            List<Activida> attachedActividaListNew = new ArrayList<Activida>();
            for (Activida actividaListNewActividaToAttach : actividaListNew) {
                actividaListNewActividaToAttach = em.getReference(actividaListNewActividaToAttach.getClass(), actividaListNewActividaToAttach.getActicodi());
                attachedActividaListNew.add(actividaListNewActividaToAttach);
            }
            actividaListNew = attachedActividaListNew;
            estrcheq.setActividaList(actividaListNew);
            estrcheq = em.merge(estrcheq);
            for (Activida actividaListOldActivida : actividaListOld) {
                if (!actividaListNew.contains(actividaListOldActivida)) {
                    actividaListOldActivida.setActilich(null);
                    actividaListOldActivida = em.merge(actividaListOldActivida);
                }
            }
            for (Activida actividaListNewActivida : actividaListNew) {
                if (!actividaListOld.contains(actividaListNewActivida)) {
                    Estrcheq oldActilichOfActividaListNewActivida = actividaListNewActivida.getActilich();
                    actividaListNewActivida.setActilich(estrcheq);
                    actividaListNewActivida = em.merge(actividaListNewActivida);
                    if (oldActilichOfActividaListNewActivida != null && !oldActilichOfActividaListNewActivida.equals(estrcheq)) {
                        oldActilichOfActividaListNewActivida.getActividaList().remove(actividaListNewActivida);
                        oldActilichOfActividaListNewActivida = em.merge(oldActilichOfActividaListNewActivida);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = estrcheq.getEschcodi();
                if (findEstrcheq(id) == null) {
                    throw new NonexistentEntityException("The estrcheq with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Estrcheq estrcheq;
            try {
                estrcheq = em.getReference(Estrcheq.class, id);
                estrcheq.getEschcodi();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The estrcheq with id " + id + " no longer exists.", enfe);
            }
            List<Activida> actividaList = estrcheq.getActividaList();
            for (Activida actividaListActivida : actividaList) {
                actividaListActivida.setActilich(null);
                actividaListActivida = em.merge(actividaListActivida);
            }
            em.remove(estrcheq);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Estrcheq> findEstrcheqEntities() {
        return findEstrcheqEntities(true, -1, -1);
    }

    public List<Estrcheq> findEstrcheqEntities(int maxResults, int firstResult) {
        return findEstrcheqEntities(false, maxResults, firstResult);
    }

    private List<Estrcheq> findEstrcheqEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Estrcheq.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Estrcheq findEstrcheq(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Estrcheq.class, id);
        } finally {
            em.close();
        }
    }

    public int getEstrcheqCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Estrcheq> rt = cq.from(Estrcheq.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
